package hosc

import scala.util.parsing.input.StreamReader
import scala.util.parsing.input.CharArrayReader

import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import java.io.FileReader
import java.io.FileWriter
import java.io.BufferedReader

import HLanguage._
import Util._

object SCLemApp {
  val help = """usage: hosc.SuperCompilerApp -si sinput_file -t tree_output_file -p program_output_file
  |Where:
  |sinput_file           path to input file (code in hl language)
  |tree_output_file      path to file where process tree will be placed (in SVG format)
  |program_output_file   path to file where residual program will be placed (in hl language)
  |""".stripMargin
  def main(args : Array[String]) : Unit = {
    var fileName: String = null
    var lemmasFileName: String = null
    var outFileName: String = null
    var outProgramFileName: String = null
    //var sugared = false
    args.toList match {
      case "-si" :: input_file :: "-li" :: lemma_file :: "-t" :: output_file :: "-p" :: output_file_1 :: Nil =>
        lemmasFileName = lemma_file
        fileName = input_file
        outFileName = output_file
        outProgramFileName = output_file_1
      case "-help" :: Nil => 
        println(help)
        return
      case _ => 
        throw new IllegalArgumentException("run hosc.SuperCompilerApp -help for help")       
    }
    
    val (program, lemmas) = programWithLemmas(fileName, lemmasFileName)
    val sc = new SCLem(program, lemmas)
    val pt = sc.buildProcessTree(program.goal)    
    val svg = new ProcessTreeSVG(pt).treeToSVG
    
    val svgFile = new java.io.File(outFileName)
    if (!svgFile.exists){
      svgFile.createNewFile()
    } 
    scala.xml.XML.save(outFileName, svg)
    
    val g = new CodeConstructor(program, pt, true)
    val p = g.generateProgram()
    val doc = p.toDoc
    val slFile = new java.io.File(outProgramFileName)
    if (!slFile.exists){
      slFile.createNewFile()
    }
    val fw = new FileWriter(slFile);
    fw.write("-- generated by hosc0 from " + fileName + "\n")
    doc.format(120, fw)
    fw.flush();
    fw.close();
  }
}
